$(document).ready(function () {
    var table = $('table#table').DataTable({
        initComplete: function(settings, json) {
            $("#table").removeClass('dataTable');
            $("#table").parent().addClass('table-responsive');

            $("#table").parent()
              .css('max-height', $(window).height() - $('#query-area').height() - 260)
              .css('height', 'auto')
              .css('overflow-y', 'visible');

            $("#table").on('change', 'input[type="checkbox"]', function () {
                if($(this).prop('checked')) {
                    $(this).closest('tr').addClass('warning');
                } else {
                    $(this).closest('tr').removeClass('warning');
                }
            });

            // 动态添加搜索条件行间距样式
        $('<style>').text(`#query-area .form-group {margin-bottom: 15px;}`).appendTo('head');

        // 动态添加表头居中样式
        $('<style>').text('#table thead th { text-align: center !important; }').appendTo('head');

        // 添加行点击事件处理
            $("#table tbody").on('click', 'tr', function(e) {
                // 避免点击复选框本身时触发两次
                if (!$(e.target).is('input[type="checkbox"]')) {
                    // 找到当前行的复选框
                    var checkbox = $(this).find('input[type="checkbox"]').first();
                    // 切换复选框状态
                    checkbox.prop('checked', !checkbox.prop('checked'));
                    // 触发change事件以更新行样式
                    checkbox.trigger('change');
                }
            });
        },
        ajax: {
            url: baseUrl + '/datatable',
            data: function (d) {
                var no        = $('.search-form').find('input[name="documentNumber"]').val();
                var type      = $('.search-form').find('select#type').val();
                var status    = $('.search-form').find('select#status').val();
                var material  = $('.search-form').find('input[name="material"]').val();
                var fromdate  = $('.search-form').find('input[name="fromdate"]').val();
                var todate    = $('.search-form').find('input[name="todate"]').val();
                d.no       = no;
                d.type     = type;
                d.status   = status;
                d.material = material;
                d.fromdate = fromdate;
                d.todate   = todate;
                return d;
            }
        },
        order: [
            [11, 'desc']
        ],
        columns: [{
            data: 'id',
            sortable: false,
            defaultContent: '',
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return '<input type="checkbox" name="ids" value="' + data + '" style="transform: scale(1.5);"/>'
            }

        }, {
            'class': 'text-center',
            name: 'documentNumber',
            data: 'documentNumber',
            render: function (data, type, row, meta) {
                return `<a hfre="#" style="text-decoration: underline"  onclick="showWavedetail(${row.id})">${row.documentNumber}</a>`;
            }
        }, {
            'class': 'text-center',
            name: 'type',
            data: 'type',
            render: function (data, type, row, meta) {
                return '先进先出';
            }
        }, {
            'class': 'text-center',
            name: 'refDocNumber',
            data: 'refDocNumber',
            render: function (data, type, row, meta) {
                return '否';
            }
        }, {
            'class': 'text-center',
            name: 'createdBy',
            data: 'createdBy'
        }, {
            'class': 'text-center',
            name: 'createdDate',
            data: 'createdDate'
        }, {
            'class': 'text-center',
            name: 'status',
            data: 'status',
            render: function (data, type, row, meta) {
                if (data == '0000')  return '创建单据';
                if (data == '0300')  return '完全分配';
                if (data == '0250')  return '部分分配';
                if (data == '0650')  return '部分拣选';
                if (data == '0700')  return '出库完成';
                if (data == '0850')  return '单据作废';
                if (data == '0880')  return '关闭';
                return data;
            }
        }, {
            'class': 'text-center',
            name: 'sortationLocationCode',
            data: 'sortationLocationCode',
            render: function (data, type, row, meta) {
                return `<a hfre="#" style="text-decoration: underline"  onclick="showOrderdetail(${row.id})">${row.sortationLocationCode}</a>`;
            }
        }, {
            'class': 'text-center',
            name: 'workHandleCode',
            data: 'workHandleCode',
            render: function (data, type, row, meta) {
                if (data=="")        return "";
                if (data==null)      return "";
                if (data==undefined) return "";
                return data.replace('2023', '东1')
                           .replace('2028', '东2')
                           .replace('2033', '东3')
                           .replace('2038', '东4')
                           .replace('1023', '西1')
                           .replace('1028', '西2')
                           .replace('1033', '西3')
                           .replace('1038', '西4')
                    ;
            }
        }, {
            data: "id",
            defaultContent: '',
            sortable: false,
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return `<button type="button" class="btn btn-default btn-xs" onclick="showWavedetail(${row.id})"><i class="fa fa-list"></i></button>`;
            }
        }, {
            data: "id",
            defaultContent: '',
            sortable: false,
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return `<button type="button" class="btn btn-default btn-xs" onclick="showOrderdetail(${row.id})"><i class="fa fa-list"></i></button>`;
            }
        }, {
            name: 'notes',
            data: 'notes'
        },
        //     {
        //     data: "enabled",
        //     defaultContent: '',
        //     sortable: false,
        //     'class': 'text-center',
        //     render: function (data, type, row, meta) {
        //         var result = '<a class="btn btn-xs btn-default enable" href="javascript:;">';
        //         if (data) {
        //             result += '<i title="激活/禁用" class="fa fa-check-square-o"/>';
        //         } else {
        //             result += '<i title="激活/禁用" class="fa fa-square-o"/>';
        //         }
        //         result += '</a>';
        //         return result;
        //     }
        // },

            {
            data: "id",
            defaultContent: '',
            sortable: false,
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return ('<div class="btn-group">' +
                    '<a class="btn btn-default btn-xs del" title="删除" href="#"><i class="fa fa-trash-o"></i></a>' +
                    '</div>' +
                    '&nbsp;&nbsp;');
            }
        }]
    });

    table.on('click', '.del', function () {
        var id = table.row($(this).parents('tr')).data().id;
        $("#delForm #ids").val(id);
        if (id) {
            bootbox.confirm("确定要删除数据吗?", function (result) {
                if (result) {
                    $("#delForm").submit();
                }
            });
        }
    });

    $(".btn.delAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#delForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要删除选中的数据吗?", function (result) {
                if (result) {
                    $("#delForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要删除的数据.");
        }
    });

    $(".btn.promptAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#promptForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要优先执行选中的数据吗?", function (result) {
                if (result) {
                    $("#promptForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择设定优先执行的数据.");
        }
    });


    $(".btn.pickstationAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#pickstationForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            $('#myModal').modal('show')
        } else {
            bootbox.alert("请选择设定拣货站台的数据.");
        }
    });

    $("#pickstations-d-allbox").on('change', function(e){
        if (this.checked) {
            document.getElementById("pickstation-d1").checked = true;
            document.getElementById("pickstation-d2").checked = true;
            document.getElementById("pickstation-d3").checked = true;
            document.getElementById("pickstation-d4").checked = true;
        } else {
            document.getElementById("pickstation-d1").checked = false;
            document.getElementById("pickstation-d2").checked = false;
            document.getElementById("pickstation-d3").checked = false;
            document.getElementById("pickstation-d4").checked = false;
        }
    });

    $("#pickstations-x-allbox").on('change', function(e){
        if (this.checked) {
            document.getElementById("pickstation-x1").checked = true;
            document.getElementById("pickstation-x2").checked = true;
            document.getElementById("pickstation-x3").checked = true;
            document.getElementById("pickstation-x4").checked = true;
        } else {
            document.getElementById("pickstation-x1").checked = false;
            document.getElementById("pickstation-x2").checked = false;
            document.getElementById("pickstation-x3").checked = false;
            document.getElementById("pickstation-x4").checked = false;
        }
    });

    $("#pickstation-btn").on("click", function (e) {
        if (isCheckboxed_(document.getElementsByName('pickstations'))) {
            $("#pickstationForm").submit();
        } else {
            bootbox.alert("请选择设定拣货站台.");
        }
    });

    $(".btn.executeAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#executeForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要执行选中的数据吗?", function (result) {
                if (result) {
                    $("#executeForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要执行的数据.");
        }
    });

    $(".btn.printSheetAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#printSheetForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要打印的选定的数据吗?", function (result) {
                if (result) {
                    $("#printSheetForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要打印的数据.");
        }
    });

    $(".btn.activeAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#activeForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要激活选定的数据吗?", function (result) {
                if (result) {
                    $("#activeForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要激活的数据.");
        }
    });

    $(".btn.closeAllActive").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#closeAllActiveForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要关闭激活选定的数据吗?", function (result) {
                if (result) {
                    $("#closeAllActiveForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要关闭激活的数据.");
        }
    });


    $(".btn.closeAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#closeForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要关闭的数据吗?", function (result) {
                if (result) {
                    $("#closeForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要关闭的数据.");
        }
    });

    $(".btn.allocateSoAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#allocateSoForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要分波选中的数据吗?", function (result) {
                if (result) {
                    $("#allocateSoForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要分波的数据.");
        }
    });

    table.on('click', '.enable', function () {
        var that = this;
        var data = table.row($(this).parents('tr')).data();
        var id = data.id;
        var enabled = data.enabled;
        bootbox.confirm("确定要更新选中的数据吗?", function (resul) {
            if (resul) {
                $.get(baseUrl + "/enable", {
                    enabled: !enabled,
                    ids: id
                }, function (res) {
                    if (res) {
                        data.enabled = !enabled;
                        $(that).find("i").removeClass("fa-" + (enabled ? "check-" : "") + "square-o").addClass("fa-" + (!enabled ? "check-" : "") + "square-o");
                        toastr.info('操作成功!');
                    }

                });
            }
        });
    });

    $('.form_datetime').datetimepicker({
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: true,
        startView: 2,
        minView: 2,
        forceParse: false,
        language: 'cn',
        calendarWeeks: true,
        pickerPosition: "bottom-left"
    }).on('changeDate', function (ev) {
        daycount = 0;
        if (null != ev.date && undefined != ev.date) {
            var day = new Date(ev.date.getYear(), ev.date.getMonth(),ev.date.getDate());
            daycount = day.getDate();
        }

    });

    $('.search-form').on("submit", function (e) {
        table.draw();
        //阻止表单submit
        return false;
    });

    function isCheckboxed_(checkboxElements) {
        var len = checkboxElements.length;
        for (var i = 0; i < len; i++) {
            if (checkboxElements[i].checked) return true;
        }

        return false;
    }

});


function showWavedetail(_id) {
    var $modal = $("#waveDetailModal");
    $modal.find("iframe").attr("src", `${rootUrl}/outbound/wavedetails/${_id}`);
    $modal.modal('show');
}

function showOrderdetail(_id) {
    console.log(_id);
    var $modal = $("#orderDetailModal");
    $modal.find("iframe").attr("src", `${rootUrl}/outbound/wavesolist/${_id}`);
    $modal.modal('show');
}
